import json
import os
from semantic_nav.log_utils import get_logger
logger = get_logger()


def read_json(file_path):
    """Reads a JSON file and returns the data as a dictionary."""
    with open(file_path, "r") as f:
        data = json.load(f)
    return data


def write_json(dict_data, path):
    """Outputs the dictionary data as a JSON file."""
    # Convert the dictionary to a JSON string
    json_data = json.dumps(dict_data)
    # Save the JSON string to a file
    with open(path, 'w') as f:
        f.write(json_data)


def convert_to_seconds(time_str):
    """Converts time string in "mm:ss" format to seconds."""
    split_list = time_str.split(":")
    if len(split_list) != 2:
        return -1.0
    minutes, seconds = map(float, split_list)
    return minutes * 60 + seconds


def process_time_json(file_path):
    """Processes the JSON file and prints timestamps in minutes:seconds format."""
    data = read_json(file_path)
    map_tree = dict()
    for scene_data in data:
        scene_name = scene_data["scene"]
        map_tree[scene_name] = dict()
        arrive_time_seconds = convert_to_seconds(scene_data["arrive_time"])
        leave_time_seconds = convert_to_seconds(scene_data["leave_time"])

        logger.info(f"Scene: {scene_name}")
        logger.info(f"  Arrive Time: {arrive_time_seconds:f} s")
        logger.info(f"  Leave Time: {leave_time_seconds:f} s")

        for waypoint, time_str in scene_data["waypoints"].items():
            if time_str != "N/A":
                waypoint_time_seconds = convert_to_seconds(time_str)
                map_tree[scene_name][waypoint] = waypoint_time_seconds
                logger.info(f"    Waypoint '{waypoint}': {waypoint_time_seconds:f} s")
            else:
                logger.info(f"    Waypoint '{waypoint}': N/A")
    return map_tree


if __name__ == '__main__':
    from ament_index_python.packages import get_package_prefix
    map_dict = process_time_json(os.path.join(get_package_prefix("semantic_nav"), "json", "time.json"))
    write_json(map_dict, os.path.join(get_package_prefix("semantic_nav"), "json", "map.json"))
